/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ep.m002.ui.controllers;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
import com.vaadin.data.util.BeanItem;
import com.vaadin.terminal.gwt.server.WebApplicationContext;
import ep.libs.implementations.AbstractModule;
import ep.persistence.entities.T002Doctor;
import ep.persistence.entities.T005Patient;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

/**
 *
 * @author skyr
 */
public class M002Controller {

    private T005Patient patient;
    private AbstractModule module;
    private WebResource service;

    public M002Controller(AbstractModule module) {
        this.module = module;
        ClientConfig config = new DefaultClientConfig();
        Client client = Client.create(config);
        config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
        service = client.resource(UriBuilder.fromUri("http://localhost:8080/EPrescribing/rest").build());
    }

    public T005Patient getPatient() {
        return patient;
    }

    public BeanItem<T005Patient> getPatientDataSource(String amka) {
        patient = service.path("bl002").path("patient").queryParam("amka", amka).
                accept(MediaType.APPLICATION_JSON).get(T005Patient.class);
        if (patient == null) {
            return null;
        } else {
            BeanItem<T005Patient> beanItem = new BeanItem<T005Patient>(patient);
            return beanItem;
        }
    }

    public boolean isDoctorEligible() {
        T002Doctor doctor = findDoctor();
        try {
            return doctor.getT004Insurances().contains(patient.getT004Insurance());
        } catch (Exception e) {
            return false;
        }

    }

    public String getAmkaByPatientObject(Object patientObj) {
        T005Patient tp = (T005Patient) patientObj;
        return tp.getAmka();
    }

    private T002Doctor findDoctor() {
        String username = (String) ((WebApplicationContext) module.getApplication().getContext()).getHttpSession().getAttribute("username");
        T002Doctor doctor = service.path("bl002").path("doctor").queryParam("username", username).
                accept(MediaType.APPLICATION_JSON).get(T002Doctor.class);
        return doctor;
    }
}
